package com.eve.springcloud.service.impl;

import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Service;

import com.eve.springcloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

import cn.hutool.core.util.IdUtil;

@Service("deptService")
@DefaultProperties(defaultFallback = "globalFallback")
public class DeptServiceImpl implements DeptService {

	@Override
	public String payment(Long id) {		
		return "当前线程池：" + Thread.currentThread().getName() + "，请求id：" + id;
	}

	@Override
	/*@HystrixCommand(fallbackMethod = "commonFallback", commandProperties = {
			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2000")
	})*/
	@HystrixCommand(commandProperties = {
			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")})
	public String paymentTimeout(Long id) {
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			
		}
		return "当前线程池：" + Thread.currentThread().getName() + "，超时请求id：" + id;
	}

	@Override
	public String commonFallback(Long id) {
		return "呀，访问的人太多了，请重试！";
	}

	public String globalFallback() {
		return "哇，服务爆满，请稍后重试！";
	}
	
	
	//////// 服务熔断 20200518
	/**
	 * 服务方法 20200518
	 * @param id
	 * @return
	 */
	@HystrixCommand(fallbackMethod = "circuitBreakerFallBack", commandProperties = {
			@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),   // 是否开启端口器
			@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),    // 请求次数
			@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), // 时间窗口期
			@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"), // 失败率达到多少后跳闸
	})
	@Override
	public String circuitBreakerDept(Long id) {
		if(id < 0) {
			throw new RuntimeException("****id不能为负数");
		}
		String serialNumber = IdUtil.simpleUUID();
		return Thread.currentThread().getName() + "线程调用成功， 流水号：" + serialNumber;
	}
	/**
	 * 熔断返回方法（出问题返回的方法）
	 * @param id
	 * @return
	 */
	public String circuitBreakerFallBack(Long id) {
		return "id 不能为负数，请稍后重试：" + id;
	}
	
}
